<template>
  <div v-loading="loading" class="tab-container">
    <!-- 查询与新增 -->
    <el-form ref="form" :model="form">
      <el-form-item>
        <el-input placeholder="请输入内容" v-model="form.queryName" @input="handleQuery()" class="wl-input">
          <el-button @click="handleQuery()" slot="append" icon="el-icon-search" class="wl-search" />
        </el-input>
        <el-button v-if="enableCreate" @click="handleAdd()" type="primary" icon="el-icon-edit" class="wl-append">添加</el-button>
      </el-form-item>
    </el-form>

    <!-- 列表 -->
    <el-table :data="list" :header-cell-style="{background:'#f4f4f5'}" class="wl-table">
      <el-table-column prop="name" :show-overflow-tooltip="true" label="空间名" width="220" />
      <el-table-column prop="user_name" :show-overflow-tooltip="true" label="空间所属人" width="220" />
      <el-table-column prop="created_at" :show-overflow-tooltip="true" label="创建时间" width="220" />
      <el-table-column prop="operate" label="操作">
        <template slot-scope="scope">
          <el-button v-if="scope.row.enable_update" @click="handleEdit(scope.row)" type="text" icon="el-icon-edit">编辑</el-button>
          <el-button v-if="scope.row.enable_delete" @click="handleDelete(scope.row)" type="text" icon="el-icon-delete" class="wl-delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="wl-pagination" background
      layout="total, sizes, prev, pager, next"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100, 150, 200]"
      :page-size="pageSize"
      :total="count">
    </el-pagination>

    <!-- 弹出space编辑容器 -->
    <el-dialog :title="dialogTitle" :visible.sync="dlgform.dialogFormVisible" v-loading.fullscreen.lock="loading" :close-on-click-modal="false" width="600px">
      <el-form ref="dlgform" :model="dlgform" :rules="rules" label-width="120px">
        <el-form-item label="空间名称" prop="spaceName">
          <el-input v-model="dlgform.spaceName" autocomplete="off" placeholder="空间名称" class="wl-input"></el-input>
        </el-form-item>
        <el-form-item label="所属人" prop="userId">
          <el-select @focus="handleFocusOwnerUser()" @change="handleUserChange($event)" v-model="dlgform.userId" placeholder="请分配用户" class="wl-input">
            <el-option v-for="item in userlist" :key="item.user_id" :label="item.username" :value="item.user_id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submitDlgForm()" type="primary">确 定</el-button>
        <el-button @click="dlgform.dialogFormVisible=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getSpace, addSpace, updateSpace, deleteSpace } from '@/api/space'
import { getUsers } from '@/api/user'

export default {
  name: 'Space',
  data() {
    return {
      loading: false,
      form: {
        queryName: ''
      },
      enableCreate: false,
      list: [],
      count: 0,
      pageSize: 10,
      currentPage: 1,
      dlgform: {
        dialogFormVisible: false,
        editStatus: 1,  //编辑状态 1：新增 2：修改
        spaceId: '',
        spaceName: '',
        userId: '',
        userName: ''
      },
      rules: {
        spaceName: [{ required: true, message: '请输入空间名称', trigger: 'blur' }],
        userId: [{ required: true, message: '请分配用户', trigger: 'blur' }]
      },
      userlist: []
    }
  },
  computed: {
    dialogTitle: function() {
      switch(this.dlgform.editStatus) {
        case 1: return '新增空间'
        case 2: return '编辑空间'
      }
    }
  },
  created() {
    // init the default selected tab
  },
  mounted() {
    this.getSpaceInfo()
  },
  methods: {
    handleQuery(event) { // 查询
      this.getSpaceInfo()
    },
    handleAdd(event) { // 新增
      this.dlgform.dialogFormVisible = true
      this.dlgform.editStatus = 1
      this.dlgform.spaceId = ''
      this.dlgform.spaceName = ''
      this.dlgform.userId = ''
      this.dlgform.userName = ''
      this.resetDlgForm()
    },
    handleEdit(row) {  // 编辑
      this.dlgform.dialogFormVisible = true
      this.dlgform.editStatus = 2
      this.dlgform.spaceId = row.id
      this.dlgform.spaceName = row.name
      this.dlgform.userId = row.user_id
      this.dlgform.userName = row.username
      if (!this.userlist || this.userlist.length<=0) {
        this.getOwnerUsers()
      }
    },
    handleDelete(row) { // 删除
      this.$confirm('确定删除该空间【' + row.name + '】吗?', '提示', {type:'warning', confirmButtonText:'确定', cancelButtonText:'取消'}).then(() => {
        this.loading = true
        deleteSpace(row.id, row.user_id).then(response => {
          this.loading = false
          if (!response.data || response.data.code !== 0) {
            this.$message({ type:'error', message:(response.data && response.data.message) ? response.data.message:'请求数据异常！' })
            return
          }
          this.getSpaceInfo()
          this.$message({ type: 'success', message: '删除成功！' })
        }).catch(error => {
          this.loading = false
          this.$message({ type: 'error', message: '删除失败!' });
        })
      });
    },
    handleFocusOwnerUser(event) { // 下拉归属人列表
      this.getOwnerUsers()
    },
    handleUserChange(userId) { // 选择归属人
      for(var i=0; i<this.userlist.length; i++) {
        if (userId === this.userlist[i].user_id) {
          this.dlgform.userName = this.userlist[i].username
          break;
        }
      }
    },
    handleSizeChange(pageSize) { // 设置分页大小事件
      this.pageSize = pageSize
      this.getSpaceInfo()
    },
    handleCurrentChange(pageno) { // 处理分页事件
      this.currentPage = pageno
      this.getSpaceInfo()
    },
    submitDlgForm() { // 提交新增Space表单
      this.$refs['dlgform'].validate((valid) => {
        if (valid) {
          switch(this.dlgform.editStatus) {
          case 1: // add
            this.loading = true
            addSpace(this.dlgform.spaceName.trim(), this.dlgform.userId, this.dlgform.userName).then(response => {
              this.loading = false
              if (!response.data || response.data.code !== 0) {
                this.$message({ type:'error', message:(response.data && response.data.message) ? response.data.message:'请求数据异常！' })
                return
              }
              this.dlgform.dialogFormVisible = false
              this.getSpaceInfo()
            }).catch(error => {
              this.loading = false
              this.$message({ type:'error', message:'请求异常！'})
              console.log(error)
            })
            break
          case 2: // edit
            this.loading = true
            updateSpace(this.dlgform.spaceId, this.dlgform.spaceName.trim(), this.dlgform.userId, this.dlgform.userName).then(response => {
              this.loading = false
              if (!response.data || response.data.code !== 0) {
                this.$message({ type:'error', message:(response.data && response.data.message) ? response.data.message:'请求数据异常！' })
                return
              }
              this.dlgform.dialogFormVisible = false
              this.getSpaceInfo()            
            }).catch(error => {
              this.loading = false
              this.$message({ type:'error', message:'请求异常！'})
              console.log(error)
            })
            break
          }
        } else {
          return false;
        }
      });
    },
    resetDlgForm() { // 重置新增Space表单
      if (this.$refs['dlgform'] !== undefined) { // 防止第一次DOM没有加载完
        this.$refs['dlgform'].resetFields()
      }
    },
    getSpaceInfo() { // 获取空间列表
      this.loading = true
      getSpace(this.pageSize, this.currentPage, this.form.queryName.trim()).then(response => {
        this.loading = false
        if (!response.data || response.data.code !== 0) {
          this.$message({ type:'error', message:(response.data && response.data.message) ? response.data.message:'请求数据异常！' })
          return
        }
        let data = response.data.data
        this.enableCreate = data.enable_create
        this.count = data.count
        this.list = data.list
        if (this.count > 0 && this.list.length==0) { // 调整PageNo
          this.currentPage = Math.ceil(this.count / this.pageSize)
          this.getSpaceInfo()
        }
      }).catch(error => {
        this.loading = false
        this.$message({ type:'error', message:'请求异常！'})
        console.log(error)
      })
    },
    getOwnerUsers() { // 获取用户列表
      getUsers(200).then(response => {
        if (!response.data || response.data.code !== 0) {
          this.$message({ message: '数据加载异常', type: 0 })
          return
        }
        let data = response.data.data
        this.userlist = data.list
      }).catch(error => {
        this.$message({ type:'error', message:'请求异常！'})
        console.log(error)
      })
    }
  }
}
</script>

<style scoped>
  .tab-container {
    margin: 20px;
  }
  .wl-table {
    width:100%;
    margin-top: 10px;
  }
  .wl-input {
    width: 250px;
  }
  .wl-search {
    background:#f5f7fa;
  }
  .wl-append {
    margin-left: 15px;
  }
  .wl-delete {
    color: #f56c6c;
  }
  .wl-pagination {
    margin-top:10px;
  }
</style>